package com.psl.action.util;

import com.psl.model.userlogin;
import com.psl.services.frame.accessuser;
import org.apache.poi.hssf.usermodel.*;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.util.List;

/**
 * Created by mioko on 2017/9/19.
 */
public class exportuser {
    public String execute() {

        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("用户列表");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow(0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();

        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("用户账号");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("用户名");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("密码");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("角色");
        cell.setCellStyle(style);

        // 第五步，写入实体数据 实际应用中这些数据从数据库得到，
        accessuser as = new accessuser();
        List list = as.queryuser();

        for (int i = 0; i < list.size(); i++) {
            row = sheet.createRow(i + 1);
            userlogin user = (userlogin) list.get(i);
            // 第四步，创建单元格，并设置值
            row.createCell((short) 0).setCellValue(user.getUserID());
            row.createCell((short) 1).setCellValue(user.getUsername());
            row.createCell((short) 2).setCellValue(user.getPassword());
            row.createCell((short) 3).setCellValue(user.getPosition_id());
        }
        // 第六步，将文件存到指定位置
        try {
            FileOutputStream fout = new FileOutputStream("/Users/mioko/desktop/userlogin.xls");
//            FileOutputStream fout = new FileOutputStream("C:\\userlogin.xls");
            wb.write(fout);
            fout.close();
            HttpServletRequest request = ServletActionContext.getRequest();
            request.setAttribute("msg", "导出成功");
        } catch (Exception e) {
            e.printStackTrace();
        }


        return "success";
    }
}
